/*
*
* my page script
* views -> my
* */

(function (gb_config, $, window, document){

    // utils
    var debounce = utilsLoad.debounce,
        maxInput = utilsLoad.maxInput,
        setCookie = utilsLoad.setCookie,
        getCookie = utilsLoad.getCookie,
        validatePhone = utilsLoad.validatePhone,
        validateEmail = utilsLoad.validateEmail,
        myLoading = utilsLoad.myLoading,
        unMyLoading = utilsLoad.unMyLoading;

    //
    var hash = window.location.hash;

    // 上传头像
    var uploadImage = function (elem, userID) {
        var file = elem.files[0],
            fileSize = 0,
            fileType = '';
        var accept = ['gif','jpg','jpeg','png'];
        if(file){
            fileSize = (file.size/1024)/1024;
            fileType = file.name.split('.').pop();
            // 5M以内
            if(accept.indexOf(fileType.toLowerCase()) < 0 || fileSize > 5){
                layer.alert('仅支持png/jpg/jpeg/gif格式图片，大小不超过5M', {
                    title: '操作提示',
                    time: 5000,
                    btn: ['关闭'],
                    shadeClose: true,
                    icon: 0
                });
                return false
            }
            var fd = new FormData();
            fd.append('multipartFile', file);
            fd.append('userId', userID);
            $.ajax({
                type: 'post',
                url: API_SIGN_URL + '/rm/userExtension/uploadHeaderImg',
                contentType: false,
                processData: false,
                data: fd,
                beforeSend() { myLoading() },
                complete() { unMyLoading() }
            }).done(res => {
                if(res.message === 'success'){
                    layer.msg('已上传头像');
                    $('.userHead').attr('src', res.data);
                    $('.user_center>img').attr('src', res.data);
                    var BASE = getCookie('USER_BASE'),
                        BASE_ARR = null;
                    if(BASE){
                        BASE_ARR = BASE.split(',');
                        BASE_ARR.splice(2, 1, res.data);
                        setCookie('USER_BASE', BASE_ARR.toString(), 7);
                    }
                }else{
                    layer.alert(res.message, {
                        title: '操作提示',
                        time: 3000,
                        btn: ['关闭'],
                        shadeClose: true,
                        icon: 2
                    })
                }
            })
        }
    };

    /*
    *  投递记录 record.ejs
    * */
    gb_config.init_record = function (){

        // 定义对象
        var thisObj = {
            filterType: $('.filterType').val(),
            //
            currentPage: function (){
                var pathname = window.location.pathname;
                var $filter = $('.filter>a,.filter>div>a');
                for(var i = 0; i<$filter.length; i++){
                    var item = $($filter[i]);
                    if(pathname === item.attr('href')){
                        item.addClass('active')
                    }
                }
            },
            /*
           * 搜索条件
           * */
            filterConfig: {
                deliverStatus: '',
                interviewStatus: '',
                isCheck: ''
            },
            // hashchange
            hashChange: function (){

                var _this = this;

                var $filter = $('.filter');
                var init_hash = decodeURIComponent(hash),
                    init_href = location.pathname + init_hash;
                $filter.find('a[href="'+ init_href +'"]')
                       .addClass('active')
                       .siblings().removeClass('active');

                if(init_hash){
                    this.filterConfig.interviewStatus = init_hash.slice(1)
                }
                this.filterRecord();

                window.onhashchange = function () {
                    var hash = decodeURIComponent(window.location.hash),
                        href = location.pathname + hash;
                    $filter.find('a[href="'+ href +'"]')
                           .addClass('active')
                           .siblings().removeClass('active');
                    if(hash){
                        _this.filterConfig.interviewStatus = hash.slice(1);
                        _this.filterRecord()
                    }
                }
            },
            //init
            init: function () {
             /*
              * 搜索条件
              * deliverStatus: 1 投递成功，2 通过初筛，3 面试，5 不合适
              * isCheck：1 已查看，0 未查看
              * interviewStatus：待接受、已接受、已拒绝
              * */
                switch (this.filterType) {
                    case '1': { // 投递成功
                        this.filterConfig.deliverStatus = '1';
                        break;
                    }
                    case '2': {// 被查看
                        this.filterConfig.isCheck = '1';
                        break;
                    }
                    case '3': {// 通过初筛
                        this.filterConfig.deliverStatus = '2';
                        break;
                    }
                    case '4': {// 邀请面试
                        this.filterConfig.deliverStatus = '3';
                        break;
                    }
                    case '5': {// 不合适
                        this.filterConfig.deliverStatus = '5';
                        break;
                    }
                }
                this.filterType !== '4' && this.filterRecord();
                this.filterType === '4' && this.hashChange();
                this.currentPage()
            },
            // empty
            $empty: `<div class="my-empty">当前没有符合条件的投递记录</div>`,
            // container
            $container: $('.recordList'),
            // render template
            renderTempt: function (item){
                var type = this.filterType;
                var { interviewInfo, position } = item,
                    title = position.statusCode !== 4
                            ? `<a class="txt-ellipsis" 
                                  href="/post/${item.deliverPositionCode}.html"
                                  target="_blank">${item.deliverPositionTitle}</a>`
                            : `<a class="txt-ellipsis off">${item.deliverPositionTitle}</a>`,
                    city = position.city.indexOf('市') >= 0 ? position.city.slice(0,-1) : position.city,
                    post = item.companyName + (city ? (' / ' + city) : '') + ' / ' + position.positionProperty,
                    salary = (position.salaryFloor/1000) + 'K-' + (position.salaryCeiling/1000) + 'K' + position.unit;
                switch (type) {
                    // 1 投递成功，2 通过初筛，3 面试，5 不合适
                    case '1':case '2':case '3':case '5': {
                        var progress = '';
                        switch (type) {
                            case '1': progress = `${item.gmtCreate.slice(0, 16)} 投递成功`;break;
                            case '2': progress = `${item.gmtCheck.slice(0, 16)} 被查看`;break;
                            case '3': progress = `${item.gmtPassFirstRound.slice(0, 16)} 通过初筛`;break;
                            case '5': progress = `${item.gmtNotFit.slice(0, 16)} 被标记为不合适，感谢你的投递`;break;
                        }
                        return `<div class="item">
                                    <div class="layui-row">
                                        <div class="layui-col-md4">
                                            ${title}
                                            <span class="post">${post}</>
                                        </div>
                                        <div class="layui-col-md4">
                                            <span class="salary">${salary}</span>
                                        </div>
                                        <div class="layui-col-md4">
                                            <div class="status"></div>
                                            <span class="progress">${progress}</span>
                                        </div>
                                    </div>
                                </div>`
                    }
                    // 4 邀请面试
                    // 待接受、已接受、已拒绝
                    case '4': {
                        var statusCls = '',
                            status = '',
                            operation = '';
                        console.log(this.filterConfig.interviewStatus);
                        switch (this.filterConfig.interviewStatus) {
                            case "":case "待接受": {
                                statusCls = 'undeal';
                                status = '待处理';
                                operation = `
                                    <button type="button" class="layui-btn acceptAudition" data-id="${item.id}">接受面试</button>
                                    <button type="button" class="layui-btn layui-btn-primary refuseAudition" data-id="${item.id}">拒绝面试</button>
                                `;
                                break;
                            }
                            case "已接受": { statusCls = 'done'; status = '已接受'; break; }
                            case "已拒绝": { statusCls = 'refuse'; status = '已拒绝'; break; }
                        }
                        return `<div class="item ${statusCls}">
                                    <div class="layui-row">
                                        <div class="layui-col-md4">
                                            ${title}
                                            <span class="post">${post}</span>
                                        </div>
                                        <div class="layui-col-md4">
                                            <span class="salary">${salary}</span>
                                        </div>
                                        <div class="layui-col-md4">
                                            <div class="status">${status}</div>
                                            <span class="progress">${interviewInfo.gmtCreate.slice(0,16)} 邀请面试</span>
                                        </div>
                                    </div>
                                    <div class="layui-row">
                                        <div class="layui-col-md4">
                                            <span class="contact">联系人：${interviewInfo.contactName}</span>
                                            <span class="phone">联系方式：${interviewInfo.phoneNum}</span>
                                            <span class="location">面试地址：${interviewInfo.interviewLocation}</span>
                                        </div>
                                        <div class="layui-col-md4">
                                            <span class="time">面试时间：${interviewInfo.interviewTime.slice(0,16)}</span>
                                        </div>
                                        <div class="layui-col-md4">${operation}</div>
                                    </div>
                                </div>`
                    }
                }
            },
            // 分页
            pagination: function (config){
                if(config.total <= 0){
                    $('#pagination').empty();
                    return false
                }
                layui.laypage.render({
                    elem: 'pagination'
                    ,count: config.total
                    ,layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
                    ,limits: [10,20,50]
                    ,prev: '<i class="layui-icon"></i>'
                    ,next: '<i class="layui-icon"></i>'
                    ,curr: config.curr
                    ,limit: config.size
                    ,first: '1'
                    ,last: '尾页'
                    ,jump: function(obj, first){
                        if(!first){
                            thisObj.filterCollect({
                                curr: obj.curr,
                                size: obj.limit
                            })
                        }
                    }
                })
            },
            // 投递记录
            filterRecord: function (config) {
                config = config || {};
                config.curr = config.curr || 1;
                config.size = config.size || 10;
                var data = {
                    pageNo: config.curr,
                    pageSize: config.size,
                    deliverStatus: this.filterConfig.deliverStatus,
                    interviewStatus: this.filterConfig.interviewStatus,
                    isCheck: this.filterConfig.isCheck
                };

                $.ajax({
                    type: 'get',
                    url: API_BASE_URL + '/userCenter/deliveryResumeRecord',
                    data: data,
                    beforeSend() { myLoading() },
                    complete() { unMyLoading() }
                }).done(res => {
                    if(res.message === 'success' && typeof res.data === 'object'){
                        var { results, totalCount } = res.data,
                            template = this.renderTempt.bind(thisObj);
                        var html = (results || []).reduce((prev, item) => {
                            return prev + template(item)
                        }, '');
                        this.$container.html(html);
                        this.pagination({
                            curr: config.curr,
                            size: config.size,
                            total: totalCount
                        });
                        // 0条数据，展示空图片
                        if(totalCount <= 0){
                            this.$container.html(thisObj.$empty)
                        }
                    }else{
                        layer.alert(res.message, {
                            title: '操作提示',
                            time: 3000,
                            btn: ['关闭'],
                            shadeClose: true,
                            icon: 2
                        })
                    }
                })
            },
            // 接受/拒绝面试
            audition: function (config) {
                config = config || {};
                var warnTxt = config.type === '已接受' ? '确认接受面试吗' : '确认拒绝面试吗';
                layer.confirm('此操作不可撤回，'+ warnTxt +'？',{
                    title: '确认消息'
                }, function(index){

                    $.ajax({
                        url: API_BASE_URL + '/userCenter/acceptOrRejectInterview',
                        data: {
                            acceptOrRejectInterviewStatus: config.status,
                            deliverRecordId: config.id
                        }
                    }).done(function (res) {
                        if(res.message === 'success'){
                            layer.msg('操作成功');
                            thisObj.filterRecord()
                        }else{
                            layer.alert(res.message, {
                                title: '操作提示',
                                time: 3000,
                                btn: ['关闭'],
                                shadeClose: true,
                                icon: 2
                            })
                        }
                    });
                    layer.close(index)
                })
            }
        };

        thisObj.init();

        // click
        thisObj.$container.on('click', function (e) {
            var $tar = $(e.target);
            var id = $tar.attr('data-id');
            // 接受面试
            if($tar.hasClass('acceptAudition')){
                thisObj.audition({
                    status: '已接受',
                    id: id
                })
            }
            // 拒绝面试
            if($tar.hasClass('refuseAudition')){
                thisObj.audition({
                    status: '已拒绝',
                    id: id
                })
            }
        })
    };


    /*
    *  职位收藏 collect.ejs
    * */
    gb_config.init_collect = function (){

        // 定义对象
        var thisObj = {
            //init
            init: function () {
                this.filterCollect()
            },
            // empty
            $empty: `<div class="my-empty">当前没有职位收藏记录</div>`,
            // container
            $container: $('.collectList'),
            //模板
            template: function (item) {
                var { company } = item;
                var city = item.city.indexOf('市') >= 0 ? item.city.slice(0,-1) : item.city;
                return `
                    <div class="item">
                        <div class="layui-row">
                            <div class="layui-col-md2">
                               ${company.logoUrl
                                    ? `<img src="${company.logoUrl}" alt="">`
                                    : `<div class="short-name">${company.companySimpleName.slice(0,4)}</div>`
                                }
                            </div>
                            <div class="layui-col-md6">
                                ${item.gmtOffline 
                                    ? `<a class="txt-ellipsis off">${item.positionTitle}</a>` 
                                    : `<a class="txt-ellipsis" href="/post/${item.positionCode}.html" target="_blank">${item.positionTitle}</a>`}
                                <span class="salary">${item.salaryFloor/1000 + 'K-' + item.salaryCeiling/1000 + 'K' + item.unit}</span>
                                <div class="post">${company.companyName} ${city ? (' / '+city) : ''} / ${item.positionProperty}</div>
                            </div>
                            <div class="layui-col-md4">
                                <span class="time">${item.gmtRelease.slice(0,10)} 发布</span>
                                <span>
                                    <a class="cancelCollect" href="javascript:;" data-code="${item.positionCode}">取消收藏</a>
                                    <span class="seperation">|</span>
                                    ${item.gmtOffline ? `<span>已下线</span>` : `<a href="/post/${item.positionCode}.html" target="_blank">去投简历</a>`}
                                </span>
                            </div>
                        </div>
                    </div>
                `
            },
            // 分页
            pagination: function (config){
                if(config.total <= 0){
                    $('#pagination').empty();
                    return false
                }
                layui.laypage.render({
                    elem: 'pagination'
                    ,count: config.total
                    ,layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
                    ,limits: [10,20,50]
                    ,prev: '<i class="layui-icon"></i>'
                    ,next: '<i class="layui-icon"></i>'
                    ,curr: config.curr
                    ,limit: config.size
                    ,first: '1'
                    ,last: '尾页'
                    ,jump: function(obj, first){
                        if(!first){
                            thisObj.filterCollect({
                                curr: obj.curr,
                                size: obj.limit
                            })
                        }
                    }
                })
            },
            // 筛选职位
            filterCollect: function (config) {
                config = config || {};
                config.curr = config.curr || 1;
                config.size = config.size || 10;
                var data = {
                    startNo: config.curr,
                    pageSize: config.size
                };
                $.ajax({
                    type: 'get',
                    url: API_BASE_URL + '/userCenter/selectCollectionPosition',
                    data: data,
                    beforeSend() { myLoading() },
                    complete() { unMyLoading() }
                }).done(res => {
                    if(res.message === 'success' && typeof res.data === 'object'){
                        var { results, totalCount } = res.data,
                            template = thisObj.template;
                        var html = (results || []).reduce((prev, item) => {
                            return prev + template(item)
                        }, '');
                        thisObj.$container.html(html);
                        thisObj.pagination({
                            curr: config.curr,
                            size: config.size,
                            total: totalCount
                        });
                        // 0条数据，展示空图片
                        if(totalCount <= 0){
                            thisObj.$container.html(thisObj.$empty)
                        }
                    }else{
                        layer.alert(res.message, {
                            title: '操作提示',
                            time: 3000,
                            btn: ['关闭'],
                            shadeClose: true,
                            icon: 2
                        })
                    }
                })
            },
            // 取消职位收藏
            collectPost: function (id) {
                layer.confirm('确认取消收藏该职位吗？',{
                    title: '确认消息'
                }, function(index){

                    $.ajax({
                        url: API_BASE_URL + '/userCenter/colllectPosition',
                        data: {
                            positionCode: id,
                            flag: 1
                        }
                    }).done(function (res) {
                        if(res.message === 'success'){
                            layer.msg('已取消收藏');
                            thisObj.filterCollect()
                        }else{
                            layer.alert(res.message, {
                                title: '操作提示',
                                time: 3000,
                                btn: ['关闭'],
                                shadeClose: true,
                                icon: 2
                            })
                        }
                    });
                    layer.close(index)
                })
            }
        };

        thisObj.init();

        // click 事件委托
        thisObj.$container.on('click', function (e) {
            var $tar = $(e.target);
            // 取消收藏
            if($tar.hasClass('cancelCollect')){
                thisObj.collectPost($tar.attr('data-code') || '')
            }
        })
    };


    /*
    *  账号设置 setting.ejs
    * */
    gb_config.init_setting = function (){

        hash = hash.slice(1);

        var thisObj = {
            //
            userID: $('.userID').val(),
            // init
            init: function () {
                // 初始化，显示窗口
                if(hash){
                    $('section.' + hash)
                        .removeClass('hidden')
                        .siblings().addClass('hidden');
                    $('a.' + hash)
                        .addClass('active')
                        .siblings().removeClass('active')
                }

                // hash change
                window.addEventListener('hashchange', function (){
                    hash = window.location.hash.slice(1);
                    $('section.' + hash)
                        .removeClass('hidden')
                        .siblings().addClass('hidden');
                })
            },
            // 设置密码
            submitPassword: function (params, elem) {
                $.ajax({
                    type: 'post',
                    url: API_SIGN_URL + '/permission/job/addNewPassword',
                    data: params,
                    beforeSend() {
                        $(elem).attr('disabled', true)
                    },
                    complete() {
                        $(elem).removeAttr('disabled')
                    }
                }).done((res) => {
                    if(res.message === 'success'){
                        layer.msg('已设置登录密码');
                        setTimeout(() => {
                            window.location.reload()
                        },  1000)
                    }else{
                        layer.alert(res.message, {
                            title: '操作提示',
                            time: 3000,
                            btn: ['关闭'],
                            shadeClose: true,
                            icon: 2
                        })
                    }
                })
            },
            // 修改密码
            updatePassword: function (params, elem) {
                $.ajax({
                    type: 'put',
                    url: API_SIGN_URL + '/permission/customer/renewPassword',
                    data: params,
                    beforeSend() {
                        $(elem).attr('disabled', true)
                    },
                    complete() {
                        $(elem).removeAttr('disabled')
                    }
                }).done((res) => {
                    if(res.message === 'success'){
                        layer.msg('已修改密码，请重新登录');
                        setCookie('USER_TOKEN', '', -1);
                        setTimeout(() => {
                            window.location.href = '/?redirect=%2Fmy%2Fresume#type=login'
                        },  800)
                    }else{
                        layer.alert(res.message, {
                            title: '操作提示',
                            time: 3000,
                            btn: ['关闭'],
                            shadeClose: true,
                            icon: 2
                        })
                    }
                })
            },
            // 修改/添加昵称
            bind_nickName: function (elem) {
                var regName = /^[\u0391-\uFFE5A-Za-z0-9]+$/g; //只能输入汉字和英文字母、数字
                var nickname = $('input[name="nickname"]').val();
                if(nickname.length < 4 || nickname.length > 20){
                    layer.msg('昵称可由中文、字母和数字组合，长度4-20位', {icon: 5});
                    return false
                }
                if(!regName.test(nickname)){
                    layer.msg('昵称可由中文、字母和数字组合，长度4-20位', {icon: 5});
                    return false
                }

                $.ajax({
                    url: API_SIGN_URL + '/rm/userInfoController/updateNickName',
                    data: {
                        nickName: nickname
                    },
                    beforeSend() {
                        $(elem).attr('disabled',true)
                    }
                }).done(function (res) {
                    if(res.message === 'success'){
                        layer.msg('昵称编辑成功');
                        var BASE = getCookie('USER_BASE'),
                            BASE_ARR = null;
                        if(BASE){
                            BASE_ARR = BASE.split(',');
                            BASE_ARR.splice(1, 1, nickname);
                            setCookie('USER_BASE', BASE_ARR.toString(), 1);
                        }
                        $.ajax({
                            url: API_SIGN_URL+'/auth/refreshAuthencationCache'
                        });
                        setTimeout(function (){
                            window.location.reload()
                        }, 800)
                    }else{
                        layer.alert(res.message, {
                            title: '操作提示',
                            time: 3000,
                            btn: ['关闭'],
                            shadeClose: true,
                            icon: 2
                        })
                    }
                })
            },
            // 绑定手机号/邮箱
            bind_PhoneEmail: function ($elem) {
                var $form = $elem.parents('form'),
                    $input = $form.find('.validateInput'),
                    $code = $form.find('.validateCode');
                var input = $input.val(),
                    code = $code.val(),
                    type = $elem.attr('data-type');
                if(type === '1' && !validatePhone(input)){
                    layer.msg('请输入正确的手机号', {icon: 5});
                    return false
                }
                if(type === '2' && !validateEmail(input)){
                    layer.msg('请输入正确的邮箱', {icon: 5});
                    return false
                }
                if(!code){
                    layer.msg('请输入验证码', {icon: 5});
                    return false
                }
                var url = '',
                    data = {
                        userId: this.userID,
                        verifyCode: code
                    };
                if(type === '1'){
                    url = API_SIGN_URL + '/rm/userExtension/bindTel';
                    Object.assign(data, {
                        tel: input
                    })
                }else {
                    url = API_SIGN_URL + '/rm/userExtension/bindEmail';
                    Object.assign(data, {
                        email: input
                    })
                }
                $reAjax({
                    method: 'put',
                    url: url,
                    data: data,
                    contentType: 'form'
                }, function (res){
                    res = res.responseJSON;
                    if(res.message === 'success'){
                        layer.msg('绑定成功');
                        setTimeout(function (){
                            window.location.reload()
                        }, 800)
                    }else{
                        layer.alert(res.message, {
                            title: '操作提示',
                            time: 3000,
                            btn: ['关闭'],
                            shadeClose: true,
                            icon: 2
                        })
                    }
                    setTimeout(function (){
                        $(elem).removeAttr('disabled')
                    }, 800)
                }, function () {
                    $elem.attr('disabled', true)
                })
            },
            // 获取邮箱/手机验证码
            getValidateCode: function ($elem, code){
                var type = $elem.attr('data-type');
                if(type === '1' && !validatePhone(code)){
                    layer.msg('请输入正确的手机号', {icon: 5});
                    return false
                }
                if(type === '2' && !validateEmail(code)){
                    layer.msg('请输入正确的邮箱', {icon: 5});
                    return false
                }
                if(type === '2'){
                    $reAjax({
                        method: 'post',
                        url: API_SIGN_URL + '/rm/userExtension/verifyEmail',
                        contentType: 'form',
                        data: {
                            email: code
                        }
                    }, function (res) {
                        res = res.responseJSON;
                        if(res.message === 'success'){
                            layer.msg('验证码已发送')
                        }else{
                            layer.alert(res.message, {
                                title: '操作提示',
                                time: 3000,
                                btn: ['关闭'],
                                shadeClose: true,
                                icon: 2
                            })
                        }
                    })
                }else {
                    $.ajax({
                        url: API_SIGN_URL + '/rm/userExtension/sendCode',
                        data: {
                            validateCodeType: '3',
                            telephone: code
                        }
                    }).done(function (res) {
                        if(res.message === 'success'){
                            layer.msg('验证码已发送')
                        }else{
                            layer.alert(res.message, {
                                title: '操作提示',
                                time: 3000,
                                btn: ['关闭'],
                                shadeClose: true,
                                icon: 2
                            })
                        }
                    })
                }
                utilsLoad.countDown($elem)
            }
        };

        thisObj.init();

        // 设置/修改密码
        var form = layui.form;

        form.verify({
            newPassword: function (value){// 验证密码长度
                if(value.length < 6 || value.length > 20){
                    return '请输入6-20位密码'
                }
            },
            reNewPassword: function (value){// 验证密码长度
                if(value.length < 6 || value.length > 20){
                    return '请输入6-20位密码'
                }
            }
        });
        // 设置密码
        form.on('submit(confirm_submit_pwd)', function (data) {
            var { newPassword,reNewPassword } = data.field;
            if(newPassword !== reNewPassword){
                layer.msg('两次输入的密码不一致', {icon: 5});
                return false
            }
            thisObj.submitPassword({
                password: reNewPassword
            }, data.elem)
        });

        // 修改密码
        form.on('submit(confirm_change_pwd)', function (data) {
            var { oldPassword,newPassword,reNewPassword } = data.field;
            if(newPassword !== reNewPassword){
                layer.msg('两次输入的新密码不一致', {icon: 5});
                return false
            }
            thisObj.updatePassword({
                oldPassword: oldPassword,
                newPassword: newPassword,
                renewPassword: reNewPassword
            }, data.elem)
        });

        // 添加 click 事件代理
        $('.captureElem').on({
            'click': function (e){
                var $tar = $(e.target);
                // 切换窗口
                if($tar.parent().hasClass('filter')){
                    $tar.addClass('active').siblings().removeClass('active')
                }
                // 上传头像，选择文件
                if($tar.hasClass('uploadImage')){
                    $('.uploadImageFile').click()
                }
                // 查看头像大图
                if($tar.hasClass('userHead')){
                    layer.open({
                        type: 1,
                        title: false,
                        area: ['auto'],
                        skin: 'layui-layer-nobg',
                        shadeClose: true,
                        content: "<img src='"+ $tar.attr('src') +"' style='max-width: 1200px' alt=''>"
                    })
                }
                // 修改/添加昵称
                if($tar.hasClass('confirm_bind_nickname')){
                    thisObj.bind_nickName($tar)
                }
                // 绑定邮箱/绑定手机号
                if($tar.hasClass('confirmBindBtn')){
                    thisObj.bind_PhoneEmail($tar)
                }
                // 获取验证码
                if($tar.hasClass('validateCodeBtn')){
                    var $form = $tar.parents('form'),
                        $input = $form.find('.validateInput');
                    thisObj.getValidateCode($tar, $input.val())
                }
                // 修改昵称/手机号/邮箱，form表单
                if($tar.hasClass('updateBind')){
                    var _id = $tar.attr('data-id'),
                        tempt = $('script#' + _id).html();
                    var $parent = $tar.parent(),
                        $form = $parent.find('form');
                    !$form.length && $parent.append(`<div class="update">${tempt}</div>`)
                }
                // 取消
                if($tar.hasClass('cancel_form')){
                    $tar.parents('.update').remove()
                }
            },
            'change': function (e) {
                var $tar = $(e.target);
                // 上传头像
                if($tar.hasClass('uploadImageFile')){
                    uploadImage(e.target, thisObj.userID)
                }
            }
        })
    };


    /*
    *  我的简历 resume.ejs
    * */
    gb_config.init_resume = function (){

        var chainPicker = pluginLoad.chainPicker;

        var form = layui.form,
            laydate = layui.laydate;

        // 初始化数据配置
        var initConfig = {
            allSandbar: null, // 洲
            allNation: [], // 国家/地区
            allProvince: null, // 省
            allCity: [], // 市
            allArea: [], // 区
            allPostType_1: null, // 所有职位 一级
            allPostType_2: [], // 二级
            allPostType_3: [],  // 三级
            allLanguage: null, // 语言对
            allCertificate: null, // 语言证书
            allIndustry_1: null, // 行业类别 一级
            allIndustry_2: [], // 二级
            companyList: [] // 工作过的公司
        };

        // 定义“我的简历”对象
        var thisObj = {
            //
            userID: $('.userID').val(),
            resumeID: $('.resumeID').val(),
            /*
            * 初始化，获取数据
            * */
            getData: {
                // 获取七大洲/国家
                allNationData: function (){
                    $reAjax({
                        url: API_BASE_URL + '/sysNationControler/selectAllRemoveChina'
                    }, function (res) {
                        res = res.responseJSON;
                        if(res.message === 'success'){
                            initConfig.allSandbar = res.data;
                            res.data.forEach(item => {
                                if(item.name === '亚洲'){
                                    initConfig.allNation.push({code: '001', name: "中国大陆", parentCode: item.code});
                                    initConfig.allNation.push({code: '002', name: "中国香港", parentCode: item.code});
                                    initConfig.allNation.push({code: '003', name: "中国澳门", parentCode: item.code});
                                    initConfig.allNation.push({code: '004', name: "中国台湾", parentCode: item.code});
                                }
                                item.sysNations.forEach(item1 => {
                                    initConfig.allNation.push(item1)
                                })
                            })
                        }else{
                            initConfig.allSandbar = []
                        }
                    })
                },
                // 获取省/市/区
                allProvinceData: function (){
                    $reAjax({
                        url: API_BASE_URL + '/sysNationControler/selectChinaAll'
                    }, function (res) {
                        res = res.responseJSON;
                        if(res.message === 'success'){
                            initConfig.allProvince = res.data;

                            res.data.forEach(item => {

                                item.sysNations.forEach(item1 => {
                                    initConfig.allCity.push(item1);

                                    item1.sysNations.forEach(item2 => {
                                        initConfig.allArea.push(item2)
                                    })
                                })
                            })
                        }else{
                            initConfig.allProvince = []
                        }
                    })
                },
                // 所有职位类型
                allPostTypeData: function () {
                    $reAjax({
                        url: API_BASE_URL + '/sysPosition/selectAllSysPosition'
                    }, function (res) {
                        res = res.responseJSON;
                        if(res.message === 'success'){
                            initConfig.allPostType_1 = res.data;
                            initConfig.allPostType_1.push({
                                name: '不限',
                                positionCode: '000',
                                sysPositions: []
                            });
                            res.data.forEach(item => {

                                item.sysPositions.forEach(item1 => {
                                    initConfig.allPostType_2.push(item1);

                                    item1.sysPositions.forEach(item2 => {
                                        initConfig.allPostType_3.push(item2)
                                    })
                                })
                            })
                        }else{
                            initConfig.allPostType_1 = []
                        }
                    })
                },
                //所有语言对
                allLanguage: function () {
                    $reAjax({
                        url: API_SIGN_URL + '/rm/language/listAll'
                    }, function (res) {
                        res = res.responseJSON;
                        if(res.message === 'success'){
                            initConfig.allLanguage = res.data.map(item => {
                                return {
                                    name: item.chineseName,
                                    value: item.englishName
                                }
                            })
                        }
                    })
                },
                //所有语言证书
                allCertificate: function () {
                    $reAjax({
                        url: API_SIGN_URL + '/rm/userExtension/listAllNewCertificateType'
                    }, function (res) {
                        res = res.responseJSON;
                        if(res.message === 'success'){
                            initConfig.allCertificate = res.data.filter(item => {
                                return item.certificateType !== 'other'
                            })
                        }
                    })
                },
                // 所有行业类别
                allIndustry: function () {
                    $reAjax({
                        method: 'post',
                        url: API_BASE_URL + '/sysTrade/selectAllSysTrade'
                    }, function (res) {
                        res = res.responseJSON;
                        if(res.message === 'success'){
                            initConfig.allIndustry_1 = res.data;
                            res.data.forEach(item => {

                                item.sysTrades.forEach(item1 => {
                                    initConfig.allIndustry_2.push(item1);
                                })
                            })
                        }else{
                            initConfig.allIndustry_1 = []
                        }
                    })
                },
                // 工作过的公司
                companyList: function () {
                    $reAjax({
                        url: API_SIGN_URL + '/rm/userExtension/listWorkExperienceByUserId',
                        data: {
                            userId: thisObj.userID
                        }
                    }, function (res) {
                        res = res.responseJSON;
                        if(res.message === 'success'){
                            initConfig.companyList = res.data.map(item => {
                                return {
                                    name: item,
                                    value: item
                                }
                            });
                            initConfig.companyList.push({
                                name: '其他',
                                value: '其他'
                            })
                        }
                    })
                }
            },
            // 判断数据是否加载成功
            isLoadedData: function (data, msg1, msg2){
                if(data === null){
                    layer.alert(msg1 || '正在获取位置数据，请稍后重试', {
                        title: '提示信息',
                        btn: ['关闭'],
                        time: 3000,
                        shadeClose: true,
                        icon: 0
                    });
                    return false
                }
                if(!data.length){
                    layer.alert(msg2 || '获取位置数据失败，请刷新页面重试', {
                        title: '提示信息',
                        btn: ['关闭'],
                        time: 3000,
                        shadeClose: true,
                        icon: 2
                    });
                    return false
                }
                return true
            },
            // 国家/地区
            allNation: function (elem){

                var isLoaded = this.isLoadedData(initConfig.allSandbar);

                if(!isLoaded) return false;

                var sandbar = [...initConfig.allSandbar],
                    nation = [...initConfig.allNation];
                chainPicker({
                    elem: elem,
                    targetElem: elem,
                    showField: 'name',
                    keyField: 'code',
                    chainField: 'parentCode',
                    level: 2,
                    data: {
                        first: sandbar,
                        second: nation
                    },
                    msg: {
                        first: '大洲',
                        second: '国家/地区'
                    },
                    style: {
                        second: 270
                    },
                    msgTempt: function (){
                        return layer.msg;
                    }
                })
            },
            // 常住地址
            allProvince: function (elem){

                var isLoaded = this.isLoadedData(initConfig.allProvince);

                if(!isLoaded) return false;

                var province = [...initConfig.allProvince],
                    city = [...initConfig.allCity],
                    area = [...initConfig.allArea];
                var sandbar = [...initConfig.allSandbar],
                    nation = [...initConfig.allNation.slice(4)];
                province.push({
                   name: '国外',
                   code: '0',
                   parentCode: '0'
                });
                city = city.concat(sandbar);
                area = area.concat(nation);
                chainPicker({
                    elem: elem,
                    targetElem: elem,
                    showField: 'name',
                    keyField: 'code',
                    chainField: 'parentCode',
                    level: 3,
                    data: {
                        first: province,
                        second: city,
                        third: area
                    },
                    msg: {
                        first: '省份/国外',
                        second: '城市/大洲',
                        third: '区县/国家地区'
                    },
                    msgTempt: function (){
                        return layer.msg;
                    }
                })
            },
            // 职位类型
            allPostType: function (elem){
                var isLoaded = this.isLoadedData(
                    initConfig.allPostType_1,
                    '正在获取职位类型数据，请稍后重试',
                    '获取职位类型数据失败，请刷新页面重试'
                );

                if(!isLoaded) return false;

                var postType_1 = initConfig.allPostType_1,
                    postType_2 = initConfig.allPostType_2,
                    postType_3 = initConfig.allPostType_3;
                chainPicker({
                    elem: elem,
                    targetElem: elem,
                    showField: 'name',
                    keyField: 'positionCode',
                    chainField: 'parentPositionCode',
                    level: 3,
                    multiple: {
                        on: true,
                        length: 2
                    },
                    data: {
                        first: postType_1,
                        second: postType_2,
                        third: postType_3
                    },
                    msg: {
                        first: '一级类型',
                        second: '二级类型',
                        third: '三级类型'
                    },
                    msgTempt: function (){
                        return layer.msg;
                    }
                })
            },
            // 工作城市
            allWorkCity: function (elem){
                var isLoaded = this.isLoadedData(initConfig.allProvince);

                if(!isLoaded) return false;

                var province = [...initConfig.allProvince],
                    city = [...initConfig.allCity],
                    sandbar = [...initConfig.allSandbar],
                    nation = [...initConfig.allNation.slice(4)];
                province.push({
                    code: '0',
                    name: '国外',
                    parentCode: '0'
                });
                city = city.concat(sandbar);
                chainPicker({
                    elem: elem,
                    targetElem: elem,
                    showField: 'name',
                    keyField: 'code',
                    chainField: 'parentCode',
                    level: 3,
                    data: {
                        first: province,
                        second: city,
                        third: nation
                    },
                    msg: {
                        first: '省份/国外',
                        second: '城市/大洲',
                        third: '国家地区'
                    },
                    style: {
                        third: 270
                    },
                    msgTempt: function (){
                        return layer.msg;
                    }
                })
            },
            // 行业类别
            allIndustry: function (elem){
                var isLoaded = this.isLoadedData(
                    initConfig.allIndustry_1,
                    '正在获取行业类别数据，请稍后重试',
                    '获取行业类别数据失败，请刷新页面重试'
                );

                if(!isLoaded) return false;

                var allIndustry_1 = initConfig.allIndustry_1,
                    allIndustry_2 = initConfig.allIndustry_2;
                chainPicker({
                    elem: elem,
                    targetElem: elem,
                    showField: 'name',
                    keyField: 'tradeCode',
                    chainField: 'parentTradeCode',
                    level: 2,
                    data: {
                        first: allIndustry_1,
                        second: allIndustry_2
                    },
                    msg: {
                        first: '一级类别',
                        second: '二级类别'
                    },
                    msgTempt: function (){
                        return layer.msg;
                    }
                })
            },
            // 薪资范围 限制
            salaryScaleLimit: function (elem){
                $(elem).selectMenu({
                    showField: 'name',
                    keyField: 'value',
                    orderBy: false,
                    data: function () {
                        var data = [],
                            min = 1;
                        if(elem.name === 'max'){
                            min = +$(elem).prev().attr('data-value');
                            min = min < 100 ? (min+1) : min;
                        }
                        for(var i = min; i <= 100; i++){
                            data.push({name: i+"K", value: i})
                        }
                        return data
                    },
                    eSelect: function (res){
                        $(elem).val(res[0].value ? res[0].name : '').attr('data-value', res[0].value);
                        elem.name === 'min' && $(elem).next().val('').attr('data-value', '')
                    }
                })
            },
            // 下拉框 派发器
            dispatchSelect: function (elem){
                var data = [],
                    isMultiple = false,
                    isSearch = false;
                switch (elem.name) {
                    // 当前求职状态
                    case "status": {
                        data = data.concat([
                            {name: '离职，随时到岗', value: '离职，随时到岗'},
                            {name: '在职，暂不考虑', value: '在职，暂不考虑'},
                            {name: '在职，考虑机会', value: '在职，考虑机会'},
                            {name: '在职，月内到岗', value: '在职，月内到岗'}
                        ]);
                        break
                    }
                    // 性别
                    case "gender": {
                        data = data.concat([
                            {name: '保密', value: '保密'},
                            {name: '男', value: '男'},
                            {name: '女', value: '女'}
                        ]);
                        break
                    }
                    // 工作类型
                    case "workType": {
                        data = data.concat([
                            {name: '全职', value: '全职'},
                            {name: '兼职', value: '兼职'},
                            {name: '实习', value: '实习'}
                        ]);
                        break
                    }
                    // 翻译年限
                    case "transYear": {
                        data = data.concat([
                            {name: '请选择', value: ''},
                            {name: '1年以下', value: '1年以下'},
                            {name: '1-3年', value: '1-3年'},
                            {name: '3-5年', value: '3-5年'},
                            {name: '5-10年', value: '5-10年'},
                            {name: '10年以上', value: '10年以上'},
                        ]);
                        break
                    }
                    // 学历
                    case "degree": {
                        data = data.concat([
                            {name: '高中及以下', value: '高中及以下'},
                            {name: '大专', value: '大专'},
                            {name: '本科', value: '本科'},
                            {name: '硕士', value: '硕士'},
                            {name: '博士', value: '博士'},
                            {name: '其他', value: '其他'}
                        ]);
                        break
                    }
                    // 母语、第一外语、第二外语
                    case "motherLan":case "firstLan":case "secondLan": {
                        isSearch = true;
                        data = data.concat([...initConfig.allLanguage]);
                        if(elem.name === 'motherLan'){
                            isMultiple = true
                        }
                        if(elem.name === 'secondLan'){
                            data.unshift({name: '请选择', value: ''})
                        }
                        break
                    }
                    // 企业名称
                    case "companyPro": {
                        data = data.concat([...initConfig.companyList]);
                        break
                    }
                }
                $(elem).selectMenu({
                    showField: 'name',
                    keyField: 'value',
                    multiple: isMultiple,
                    search: isSearch,
                    orderBy: false,
                    data: data,
                    eSelect: function (res){
                        var valueStr = '',
                            dataValue = res[0].value;
                        if(isMultiple){
                            res.forEach(item => {
                                valueStr += item.name + ','
                            });
                            valueStr = valueStr.slice(0, -1)
                        }else{
                            valueStr = res[0].value ? res[0].name : ''
                        }
                        $(elem).val(valueStr).attr('data-value', dataValue)
                    }
                })
            },
            // 编辑简历 派发器
            dispatchEdit: function (type, data){

                if(!type || !data) return false;

                data = JSON.parse(data);

                var $form = $('.' + type),
                    $rangeTime = null,
                    $rangeTimeToNow = null;

                switch (type) {
                    // 期望职位
                    case 'resume_post': {
                        var min = data.salaryFloor/1000,
                            max = data.salaryCeiling/1000;
                        var city = '',
                            postType = data.firstPositionCategory
                                ? (data.firstPositionCategory + '-' + data.secondPositionCategory + '-'+ data.thirdPositionCategory)
                                : '不限';
                        if(data.province){
                            city = data.province + (data.city && ("-"+data.city) || '')
                        }else{
                            city = '国外-' + data.continent + '-' + data.country
                        }
                        $form.find('[name="post"]').val(data.positionTitle);
                        $form.find('[name="postType"]').attr('title', postType).val(postType);
                        $form.find('[name="workType"]').val(data.positionProperty);
                        $form.find('[name="city"]').attr('title', city).val(city);
                        $form.find('[name="min"]').attr('data-value', min).val(min+'K');
                        $form.find('[name="max"]').attr('data-value', max).val(max+'K');
                        $form.find('button[lay-submit]').attr('data-id', data.id);
                        break
                    }
                    // 语言信息
                    case 'resume_language': {
                        $form.find('[name="motherLan"]').val(data.motherTongue);
                        $form.find('[name="transYear"]').val(data.translateYear);
                        $form.find('[name="firstLan"]').attr('data-value', data.firstLanguageCode).val(data.firstLanguage);
                        $form.find('[name="firstLanLevel"]').val(data.firstLanguageLevel);
                        $form.find('[name="secondLan"]').attr('data-value', data.secondLanguageCode).val(data.secondLanguage);
                        $form.find('[name="secondLanLevel"]').val(data.secondLanguageLevel);
                        break
                    }
                    // 工作经历
                    case 'resume_work': {
                        var industry = data.firstIndustryCategory + (data.secondIndustryCategory ? ('-'+data.secondIndustryCategory) : ''),
                            location = data.province + (data.city ? ('-' + data.city) : '');
                        var isAbroad = true;

                        if(data.province.indexOf('省') >= 0 || data.province.indexOf('市') >= 0 || data.province.indexOf('区') >= 0){
                            isAbroad = false
                        }
                        if(isAbroad){
                            location = '国外-' + location
                        }
                        $form.find('[name="company"]').val(data.companyName);
                        $form.find('[name="industry"]').attr('title', industry).val(industry);
                        $form.find('[name="workName"]').val(data.positionName);
                        $form.find('[name="location"]').attr('title', location).val(location);
                        $form.find('[name="workContent"]').val(data.workDescribe);
                        $form.find('.maxLength').html(`${data.workDescribe.length}/1500`);
                        $form.find('button[lay-submit]').attr('data-id', data.id);
                        break
                    }
                    // 项目经历
                    case 'resume_project': {
                        $form.find('[name="project"]').val(data.projectName);
                        $form.find('[name="companyPro"]').val(data.companyName);
                        $form.find('[name="projectContent"]').val(data.projectDescribe);
                        $form.find('.maxLength').html(`${data.projectDescribe.length}/1500`);
                        $form.find('button[lay-submit]').attr('data-id', data.id);
                        break
                    }
                    // 教育经历
                    case 'resume_education': {
                        if(data.schoolExperience){
                            $form.find('[name="eduContent"]').val(data.schoolExperience);
                            $form.find('.maxLength').html(`${data.schoolExperience.length}/800`)
                        }
                        $form.find('[name="school"]').val(data.graduatedSchoolName);
                        $form.find('[name="degree"]').val(data.degree);
                        $form.find('[name="major"]').val(data.major);
                        $form.find('button[lay-submit]').attr('data-id', data.id);
                        break
                    }
                }

                // rangeTime ~ 至今
                if(type === 'resume_work' || type === 'resume_project' || type === 'resume_education'){
                    var rangeTime = (data.startDatetime || data.startDate)
                                    + ' ~ '
                                    + (data.endDatetime || data.graduatedDate);
                    $rangeTime = $form.find('[name="rangeTime"]');
                    $rangeTimeToNow = $form.find('[name="toNow"]');
                    if(data.endDatetime && data.endDatetime.indexOf('至今') >= 0
                    || data.graduatedDate && data.graduatedDate.indexOf('至今') >= 0){
                        var chain = $rangeTimeToNow.attr('lay-chain'),
                            $clone = $rangeTime.clone().removeAttr('lay-key');
                        $rangeTimeToNow.prev().remove();
                        $rangeTimeToNow.before($clone);
                        $rangeTimeToNow[0].checked = true;
                        laydate.render({
                            elem: '.'+chain,
                            type: 'month',
                            value: (data.startDatetime || data.startDate),
                            max: '至今' });
                        form.render()
                    }else{
                        $rangeTime.val(rangeTime)
                    }
                }
            },
            // 编辑简历，基本信息
            fill_resume_addBase: function (data){

                if(!data) return false;
                data = JSON.parse(data);

                var $form = $('.baseForm');
                $form.find('[name="realName"]').val(data.userName);
                $form.find('[name="status"]').val(data.status);
                $form.find('[name="gender"]').val(data.sex);
                $form.find('[name="birth"]').val(data.birthday && data.birthday.slice(0, 10));
                $form.find('[name="startWork"]').val(data.workYear);
                $form.find('[name="nation"]').attr('title', data.nation).val(data.nation.replace(/\s/g, '-'));
                $form.find('[name="location"]').attr('title', data.location).val(data.location);
                $form.find('[name="telephone"]').val(data.phone);
                $form.find('[name="email"]').val(data.email);
                data.isCertificate && $form.find('[name="realName"]').attr('disabled', true) // 已认证，不能修改姓名
            },
            // 编辑自我评价
            fill_resume_addLabel: function (data){

                if(!data) return false;

                data = JSON.parse(data);

                var $form = $('.labelForm'),
                    $defaultLabel = $('.defaultLabel'),
                    $moreLabel = $('.moreLabel'),
                    $selfLabel = $('.selfLabel'),
                    $defaultLabels = $('.defaultLabel>label');
                var labels = null,
                    selfLabel = '';
                if(data.personalityLabel){
                    labels = data.personalityLabel.split(',');
                    Array.prototype.slice.call($defaultLabels).forEach(item => {
                        var _this = item,
                            label = item.innerHTML;
                        var index = labels.indexOf(label);
                        if(index >= 0){
                            $(_this).addClass('selected');
                            $defaultLabel.addClass('more');
                            $moreLabel.html('收起');
                            labels.splice(index, 1)
                        }
                    });

                    labels.forEach(item => {
                        selfLabel += `<label class="selected">${item}</label>`
                    });
                    $selfLabel.find('label').remove();
                    $selfLabel.prepend(selfLabel)
                }
                if(data.selfEvaluation){
                    $form.find('[name="short"]').val(data.selfEvaluation);
                    $form.find('.maxLength').html(`${data.selfEvaluation.length}/300`)
                }
            },
            // init
            init: function (){

                if(hash){
                    $("a[href="+ hash +"]")
                        .addClass('current')
                        .siblings().removeClass('current')
                }

                laydate.render({ elem: '.birthTime', min: '1949-01-01', max: '至今' });
                laydate.render({ elem: '.startWorkTime', type: 'month', max: '至今'});

                var { getData } = this;

                getData.allNationData();
                getData.allProvinceData();
                getData.allPostTypeData();
                getData.allLanguage();
                getData.allCertificate();
                getData.allIndustry();
                getData.companyList();

                this.resume_files();

                // 输入内容格式验证
                form.verify({
                    // 验证手机号
                    telephone: function (value){
                        if(!(validatePhone(value) || /[0-9-()（）]{7,18}/.test(value))){
                            return '请输入正确的电话号码'
                        }
                    },
                    // 验证邮箱
                    email: function (value){
                        if(!validateEmail(value)){
                            return '请输入正确的电子邮箱'
                        }
                    }
                });

                /*
                * 提交表单
                * */

                var _this = this;

                // 基本信息
                form.on('submit(resume_base_btn)', function (data) {
                    var { field } = data,
                        location = field.location.split('-');
                    var _data = {
                        "province": location[0],
                        "city": location[1] || '',
                        "county": location[2] || '',
                        "nation": field.nation.replace(/-/g, ' '),
                        "email": field.email,
                        "realName": filterXSS(field.realName),
                        "sex": field.gender,
                        "statusOfSeekingJob": field.status,
                        "tel": field.telephone,
                        "workYears": field.startWork,
                        "birthDay": field.birth
                    };
                    _this.resume_itemAdd({
                        url: API_BASE_URL + '/userCenter/modifyBasicInfo',
                        data: JSON.stringify(_data)
                    }, data.elem)
                });

                // 期望职位
                form.on('submit(resume_post_btn)', function (data) {
                    var { field } = data,
                        postType = field.postType,
                        location = field.city.split('-');
                    var isAboard = location.indexOf('国外') >= 0;
                    isAboard && location.splice(0, 1);
                    if(postType !== '不限'){
                        postType = postType.split('-')
                    }else{
                        postType = []
                    }
                    var _data = {
                        "positionTitle": filterXSS(field.post),
                        "positionFirstProperty": postType[0] || '',
                        "positionSecondProperty": postType[1] || '',
                        "positionThirdProperty": postType[2] || '',
                        "province": !isAboard ? location[0] : '',
                        "city": !isAboard ? location[1] : '',
                        "continent": isAboard ? location[0] : '',
                        "country": isAboard ? location[1] : '',
                        "locationCode": isAboard ? '1' : '0', // 0 国内， 1 国外
                        "positionProperty": field.workType,
                        "salaryFloor": +(field.min.slice(0,-1)) * 1000,
                        "salaryCeiling": +(field.max.slice(0,-1)) * 1000
                    };
                    // 修改
                    if($(data.elem).attr('data-id')){
                        _data.id = $(data.elem).attr('data-id')
                    }
                    _this.resume_itemAdd({
                        url: API_BASE_URL + '/userCenter/modifyPositionIntension',
                        data: JSON.stringify(_data)
                    }, data.elem)
                });

                // 语言信息
                form.on('submit(resume_language_btn)', function (data) {
                    var { field } = data;
                    var $form = $('.resume_language'),
                        firstLanCode = $form.find('[name="firstLan"]').attr('data-value'),
                        secondLanCode = $form.find('[name="secondLan"]').attr('data-value');
                    if(field.secondLanLevel && !field.secondLan){
                        layer.msg('请选择第二外语', {icon: 5});
                        return false
                    }
                    if(field.secondLan && !field.secondLanLevel){
                        layer.msg('请填写对应等级', {icon: 5});
                        return false
                    }
                    var _data = {
                        "firstLanguage": field.firstLan,
                        "firstLanguageCode": firstLanCode || '',
                        "firstLanguageLevel": filterXSS(field.firstLanLevel),
                        "motherTongue": field.motherLan,
                        "secondLanguage": filterXSS(field.secondLan),
                        "secondLanguageCode": secondLanCode || '',
                        "secondLanguageLevel": field.secondLanLevel,
                        "translateYears": field.transYear
                    };
                    _this.resume_itemAdd({
                        url: API_BASE_URL + '/userCenter/modifyLanguageInfo',
                        data: JSON.stringify(_data)
                    }, data.elem)
                });

                // 工作经历
                form.on('submit(resume_work_btn)', function (data) {
                    var { field } = data,
                        industry = field.industry.split('-'),
                        rangeTime = field.rangeTime.split(' ~ '),
                        location = field.location.split('-');
                    location.indexOf('国外') >= 0 && location.splice(0, 1);

                    var _data = {
                        "userId": _this.userID,
                        "companyName": filterXSS(field.company),
                        "firstIndustryCategory": industry[0],
                        "secondIndustryCategory": industry[1] || '',
                        "positionName": filterXSS(field.workName),
                        "startDatetime": rangeTime[0],
                        "endDatetime": rangeTime[1] ? rangeTime[1] : '至今',
                        "province": location[0],
                        "city": location[1] || '',
                        "describe": filterXSS(field.workContent)
                    };
                    // 修改
                    if($(data.elem).attr('data-id')){
                        _data.id = $(data.elem).attr('data-id')
                    }
                    _this.resume_itemAdd({
                        url: API_SIGN_URL + '/rm/userExtension/addWorkExperience',
                        contentType: 'form',
                        data: _data
                    }, data.elem)
                });

                // 项目经历
                form.on('submit(resume_project_btn)', function (data) {
                    var { field } = data,
                        rangeTime = field.rangeTime.split(' ~ ');

                    var _data = {
                        "userId": _this.userID,
                        "projectName": filterXSS(field.project),
                        "companyName": field.companyPro,
                        "startDatetime": rangeTime[0],
                        "endDatetime": rangeTime[1] ? rangeTime[1] : '至今',
                        "describe": filterXSS(field.projectContent)
                    };
                    // 修改
                    if($(data.elem).attr('data-id')){
                        _data.id = $(data.elem).attr('data-id')
                    }
                    _this.resume_itemAdd({
                        url: API_SIGN_URL + '/rm/userExtension/addProgramExperience',
                        contentType: 'form',
                        data: _data
                    }, data.elem)
                });

                // 教育经历
                form.on('submit(resume_education_btn)', function (data) {
                    var { field } = data,
                        rangeTime = field.rangeTime.split(' ~ ');

                    var _data = {
                        "userId": _this.userID,
                        "graduatedSchoolName": filterXSS(field.school),
                        "degree": field.degree,
                        "major": filterXSS(field.major),
                        "startDate": rangeTime[0],
                        "graduatedDate": rangeTime[1] ? rangeTime[1] : '至今',
                        "schoolExperience": filterXSS(field.eduContent)
                    };
                    // 修改
                    if($(data.elem).attr('data-id')){
                        _data.id = $(data.elem).attr('data-id')
                    }
                    _this.resume_itemAdd({
                        url: API_SIGN_URL + '/rm/userExtension/addEducationInfo',
                        contentType: 'form',
                        data: _data
                    }, data.elem)
                });

                // 自我评价
                form.on('submit(resume_self_btn)', function (data) {
                    var { field } = data;
                    var $form = $('form.labelForm'),
                        $labels = $form.find('label.selected');
                    if(!field.short && $labels.length < 1){
                        layer.msg('请选择标签/填写自我介绍', {icon: 5});
                        return false
                    }
                    var labels = Array.prototype.slice.call($labels).reduce((prev, item) => {
                        return prev + item.innerHTML + ','
                    }, '');
                    labels = labels.slice(0, -1);
                    _this.resume_addSelfLabel({
                        "individualization": labels,
                        "selfEvaluation": filterXSS(field.short)
                    }, data.elem)
                });

                // 非正式环境 打印
                getCookie('CURRENT_ENV') !== 'production' && $reAjax({
                    url: API_BASE_URL+'/userCenter/getResumeInfoOfJobSystem'
                }, function (res) {
                    res = res.responseJSON;
                    console.log(res);
                })
            },
            // 渲染 "layui-form"
            renderForm: function (partId){

                laydate.render({ elem: '.workRangeTime', type: 'month', range: '~', max: '至今' });
                laydate.render({ elem: '.projectRangeTime', type: 'month', range: '~', max: '至今' });
                laydate.render({ elem: '.eduRangeTime', type: 'month', range: '~', max: '至今' });

                // 技能证书
                if(partId === 'resume_skill' && initConfig.allCertificate){
                    var html = '',
                        allLanguage = [];
                    initConfig.allCertificate.forEach(item => {
                        if(!allLanguage.length || (allLanguage[0] && allLanguage[0].languageName !== item.languageName)){
                            allLanguage.unshift(item)
                        }
                    });
                    allLanguage = allLanguage.reverse();
                    allLanguage.forEach(item => {
                        html += `<option value="${item.languageName}">${item.languageName}</option>`
                    });
                    $('select.languageType').append(html)
                }

                form.render();

                // 选择“至今”
                form.on('checkbox(date_to_now)', function(data){
                    var _this = data.elem,
                        value = $(_this).prev().val(),
                        chain = $(_this).attr('lay-chain'),
                        $clone = $(_this).prev().clone().removeAttr('lay-key');
                    value = value && value.slice(0, 7) || '';
                    $(_this).prev().remove();
                    $(_this).before($clone);
                    if(_this.checked){
                        laydate.render({ elem: '.'+chain, type: 'month', value: value, max: '至今' })
                    }else{
                        laydate.render({ elem: '.'+chain, type: 'month', range: '~', max: '至今' })
                    }
                })
            },
            // 自定义标签
            defineLabel: function (elem){
                layer.open({
                    type: 1,
                    title: '自定义标签',
                    area: ['400px'],
                    content:`<form class="layui-form label" onsubmit="return false">
                                    <div class="layui-form-item">
                                        <input type="text" name="label" class="layui-input" required lay-verify="required" placeholder="请输入标签（最多不超过8个字符）">
                                    </div>
                                    <div class="layui-form-item">
                                        <button class="layui-btn" type="button" lay-submit lay-filter="add_selfLabel_btn">确定</button>
                                        <button class="layui-btn layui-btn-primary" type="button" onclick="layer.closeAll()">取消</button>
                                    </div>
                                 </form>`,
                    success: function (){
                        form.on('submit(add_selfLabel_btn)', function(data){
                            if(data.field.label.length > 8){
                                layer.msg('最多不超过8个字符', {icon: 5});
                                return false
                            }
                            $(elem).before(`<label>${data.field.label}</label>`);
                            layer.closeAll()
                        })
                    }
                })
            },
            /*
            * ajax HTTP request
            *
            * */
            // 添加附件简历
            upload_resumeFile: function (target) {
                var files = target.files,
                    file = '',
                    fileSize = 0,
                    fileType = '';
                var accept = ['doc','docx','pdf','jpg','jpeg','png'];

                if(files.length){
                    file = files[0];
                    fileSize = (file.size/1024)/1024;
                    fileType = file.name.split('.').pop();
                    // 10M以内
                    if(accept.indexOf(fileType.toLowerCase()) < 0 || fileSize > 10){
                        layer.alert('仅支持doc、docx、pdf、jpg和png类型文件，大小不超过10M', {
                            title: '操作提示',
                            time: 5000,
                            btn: ['关闭'],
                            shadeClose: true,
                            icon: 0
                        });
                        return false
                    }
                    var fd = new FormData();
                    fd.append('multipartFile', file);
                    $.ajax({
                        type: 'post',
                        url: API_SIGN_URL + '/rm/userExtension/uploadResumeFile',
                        contentType: false,
                        processData: false,
                        data: fd,
                        beforeSend() { myLoading() },
                        complete() { unMyLoading() }
                    }).done(res => {
                        if(res.message === 'success'){
                            layer.msg('已上传附件简历');
                            thisObj.resume_files()
                        }else{
                            layer.alert(res.message, {
                                title: '操作提示',
                                time: 3000,
                                btn: ['关闭'],
                                shadeClose: true,
                                icon: 2
                            })
                        }
                    })
                }
            },
            // 附件简历列表
            resume_files: function () {
                var $file = $('.uploadResumeFile'),
                    $add = `<a class="add-icon uploadFile" href="javascript:void(0);"
                               data-tips="仅支持doc/docx/pdf/jpg/png格式文件，大小不超过10M"
                               onmouseenter="layer.tips(this.getAttribute('data-tips'), '.uploadFile', {tips: 3, time: 30000})"
                               onmouseleave="$('.layui-layer-tips').remove()"
                            >添加</a>`;
                $reAjax({
                    url: API_SIGN_URL + '/rm/userExtension/listResumeFiles'
                }, function (res) {
                    res = res.responseJSON;
                    if(res.message === 'success'){
                        var html = (res.data || []).reduce((prev,item) => {
                            var { originFile,preview } = item;
                            return prev + `
                                    <div class="item">
                                        <a href="${preview.visitUrl}" target="_blank" title="${originFile.fileName}">${originFile.fileName}</a>
                                        <div class="resume-file">
                                            <a href="${preview.visitUrl}" target="_blank">预览</a>
                                            <a href="${originFile.visitUrl}" download target="_blank">下载</a>
                                            <div class="delete del_file" data-id="${originFile.id}">删除</div>
                                        </div>
                                    </div>
                            `
                        }, '');
                        $('div.files').html(html);

                        if(res.data.length >= 3){
                            $file.next().remove()
                        }else{
                            if($file.next().length){
                                return false
                            }
                            $file.after($add)
                        }
                    }else{
                        $file.after($add)
                    }
                })
            },
            // 删除附件简历
            resume_filesDel: function (id) {
                layer.confirm('确认删除该附件简历吗？',{
                    title: '确认消息'
                }, function(index){
                    $reAjax({
                        method: 'delete',
                        url: API_SIGN_URL + "/rm/userExtension/deleteResumeFile?fileId=" + id
                    }, function (res) {
                        res = res.responseJSON;
                        if(res.message === 'success'){
                            layer.msg('已删除附件简历');
                            thisObj.resume_files()
                        }else{
                            layer.alert(res.message, {
                                title: '操作提示',
                                time: 3000,
                                btn: ['关闭'],
                                shadeClose: true,
                                icon: 2
                            })
                        }
                    });
                    layer.close(index)
                })
            },
            /*
            * 删除简历信息 派发器
            *
            * 1、期望职位 3、项目经历
            * 2、工作经历 4、教育经历 5、技能证书
            * */
            resume_itemDel: function (conf) {
                var url = '';
                var $delItem = conf.elem.parents('.item'),
                    $parents = conf.elem.parents('.resume-item');
                switch (conf.name) {
                    case 'certificate': {
                        url = '/rm/userExtension/deleteSkillInfo';
                        $delItem = conf.elem.parents('li');
                        $parents = null;
                        break;
                    }
                    case 'resume_post': {
                        url = '/job/userCenter/deletePositionIntension';
                        break;
                    }
                    case 'resume_work': {
                        url = '/rm/userExtension/deleteWorkExperienceInfo';
                        break;
                    }
                    case 'resume_project': {
                        url = '/rm/userExtension/deleteProjectExperienceInfo';
                        break;
                    }
                    case 'resume_education': {
                        url = '/rm/userExtension/deleteEducationInfo';
                        break;
                    }
                }
                var itemLen = $delItem.siblings().length;
                layer.confirm('确认删除该条信息吗？',{
                    title: '确认消息'
                }, function(index){
                    $reAjax({
                        method: 'delete',
                        url: API_SIGN_URL + url + '?id=' + conf.id
                    }, function (res) {
                        res = res.responseJSON;
                        if(res.message === 'success'){
                            layer.msg('已删除该条信息');
                            if(itemLen < 2 && $parents){
                                $parents.find('.del_item').remove()
                            }
                            if(itemLen < 1 && !$parents){
                                $delItem.parents('.item').remove()
                            }
                            $delItem.remove();
                            // 后续操作
                            switch (conf.name) {
                                // 删除期望职位，重置 添加按钮
                                case 'resume_post': {
                                    if($parents.find('.add_form').length < 1){
                                        $parents.find('.resume-title').append(`<a href="javascript:;" class="add-icon add_form">添加</a>`)
                                    }
                                    break;
                                }
                                // 删除工作经历，重新请求所有公司数据
                                case 'resume_work': {
                                    thisObj.getData.companyList();
                                    break;
                                }
                                // 删除教育经历，刷新页面，重置个人基本信息最高学历
                                case 'resume_education': {
                                    setTimeout(function () {
                                        window.location.reload()
                                    }, 500);
                                    break;
                                }
                            }
                        }else{
                            layer.alert(res.message, {
                                title: '操作提示',
                                time: 3000,
                                btn: ['关闭'],
                                shadeClose: true,
                                icon: 2
                            })
                        }
                    });
                    layer.close(index)
                })
            },
            /*
            * 添加/修改简历信息 派发器
            *
            * 1、基本信息 2、期望职位 3、语言信息
            * 4、工作经历 5、项目经历 6、教育经历
            *
            * */
            resume_itemAdd: function (params, elem){
                params = Object.assign({}, params, {
                    method: 'post'
                });
                $reAjax(params, function (res) {
                    res = res.responseJSON;
                    if(res.message === 'success'){
                        layer.msg('操作成功');
                        thisObj.resume_update();
                        setTimeout(() => {
                            window.location.reload()
                        }, 600)
                    }else{
                        layer.alert(res.message, {
                            title: '操作提示',
                            time: 3000,
                            btn: ['关闭'],
                            shadeClose: true,
                            icon: 2
                        })
                    }
                    setTimeout(() => {
                        $(elem).removeAttr('disabled')
                    }, 600)
                }, function () {
                    $(elem).attr('disabled', true)
                })
            },
            // 更新在线简历的gmtUpdate：更新工作经历、项目经历、教育经历、技能证书时调用
            resume_update: function (){
                $.ajax({
                    type: 'put',
                    url: API_BASE_URL + '/userCenter/updateResumeGmtUpdate'
                })
            },
            // 添加/修改自我评价
            resume_addSelfLabel: function (params, elem){
                $reAjax({
                    method: 'post',
                    url: API_SIGN_URL + '/rm/userExtension/addIndividualInfo',
                    contentType: 'form',
                    data: params
                }, function (res) {
                    res = res.responseJSON;
                    if(res.message === 'success'){
                        layer.msg('操作成功');
                        setTimeout(() => {
                            window.location.reload()
                        }, 600)
                    }else{
                        layer.alert(res.message, {
                            title: '操作提示',
                            time: 3000,
                            btn: ['关闭'],
                            shadeClose: true,
                            icon: 2
                        })
                    }
                    setTimeout(() => {
                        $(elem).removeAttr('disabled')
                    }, 600)
                }, function () {
                    $(elem).attr('disabled', true)
                })
            },
            // 选择证书文件
            certificateChoseFile: function (elem){
                var file = elem.files[0],
                    fileSize = 0,
                    fileType = '';
                var accept = ['jpg','jpeg','png'];
                var $clone = null;
                if(file){
                    fileSize = (file.size/1024)/1024;
                    fileType = file.name.split('.').pop();
                    // 5M以内
                    if(accept.indexOf(fileType.toLowerCase()) < 0 || fileSize > 5){
                        elem.value = '';
                        layer.alert('仅支持png/jpg/jpeg格式图片，大小不超过5M', {
                            title: '操作提示',
                            time: 5000,
                            btn: ['关闭'],
                            shadeClose: true,
                            icon: 0
                        });
                        return false
                    }
                    if($(elem).next().length){
                        $(elem).next().remove()
                    }
                    $clone = $(elem).clone();
                    $clone.removeClass('choseCertificateFile').addClass('hidden');
                    $(elem).after($clone).attr('data-file', 'be')
                }else{
                    if($(elem).attr('data-file')){
                        $clone = $(elem).next().clone();
                        $clone.removeClass('choseCertificateFile').addClass('hidden');
                        $(elem).next()
                            .removeClass('hidden')
                            .addClass('choseCertificateFile')
                            .attr('data-file', 'be');
                        $(elem).next().after($clone).attr('data-file', 'be');
                        $(elem).remove()
                    }
                }
            },
            // 添加证书（语言/其他证书）
            certificateUpload: function (elem) {

                var isOther = elem.hasClass('other');
                var fd = new FormData();
                fd.append('userId', this.userID);
                fd.append('certificateType', isOther?'other':'linguistics');
                //验证
                if(isOther){
                    var $file = $('.choseCertificateFile.other');
                    var otherValue = $('.otherCertificate').val(),
                        otherValueFill = $('.otherCertificateName').val();
                    if(!otherValue){
                        layer.msg("请选择证书名称", {icon: 5});
                        return false
                    }else{
                        if(otherValue === '其他' && !otherValueFill){
                            layer.msg("请输入证书名称", {icon: 5});
                            return false
                        }
                    }
                    if($file.val()){
                        fd.append('multipartFile', $file[0].files[0]);
                    }
                    fd.append('certificateName', otherValue !== '其他' ? otherValue : filterXSS(otherValueFill))
                }
                else{
                    var $file = $('.choseCertificateFile');
                    var s_lanType = $('select.languageType').val(),
                        s_certificateName = $('select.certificateName').val(),
                        s_certificateLevel = $('select.certificateLevel').val(),
                        i_lanType = $('input.languageType').val(),
                        i_certificateName = $('input.certificateName').val(),
                        i_certificateLevel = $('input.certificateLevel').val();

                    if(!s_lanType){
                        layer.msg("请先选择语种", {icon: 5});
                        return false
                    }
                    else{

                        if(s_lanType !== '其他'){

                            if(!s_certificateName){
                                layer.msg("请选择证书名称", {icon: 5});
                                return false
                            }else{

                                if(s_certificateName !== '其他'){

                                    if(!s_certificateLevel){
                                        layer.msg("请选择证书等级", {icon: 5});
                                        return false
                                    }
                                    fd.append('certificateName', s_certificateName);
                                    fd.append('cerficateLevel', s_certificateLevel !== '无' ? s_certificateLevel : '')
                                }else{
                                    if(!i_certificateName || !i_certificateLevel){
                                        layer.msg("请输入证书名称/证书等级", {icon: 5});
                                        return false
                                    }
                                    fd.append('certificateName', filterXSS(i_certificateName));
                                    fd.append('cerficateLevel', filterXSS(i_certificateLevel))
                                }
                            }
                            fd.append('languageName', s_lanType)
                        }
                        else{
                            if(!i_lanType || !i_certificateName || !i_certificateLevel){
                                layer.msg("请输入语种/证书名称/证书等级", {icon: 5});
                                return false
                            }
                            fd.append('languageName', filterXSS(i_lanType));
                            fd.append('certificateName', filterXSS(i_certificateName));
                            fd.append('cerficateLevel', filterXSS(i_certificateLevel))
                        }
                    }
                    if($file.val()){
                        fd.append('multipartFile', $file[0].files[0])
                    }
                }
                $.ajax({
                    type: 'post',
                    url: API_SIGN_URL + '/rm/userExtension/addSkillInfo',
                    contentType: false,
                    processData: false,
                    data: fd,
                    beforeSend() {
                        myLoading();
                        elem.attr('disabled', true)
                    },
                    complete() {
                        unMyLoading();
                        elem.removeAttr('disabled')
                    }
                }).done(res => {
                    if(res.message === 'success'){
                        layer.msg('已上传证书');
                        setTimeout(() => {
                            window.location.reload()
                        }, 600)
                    }else{
                        layer.alert(res.message, {
                            title: '操作提示',
                            time: 3000,
                            btn: ['关闭'],
                            shadeClose: true,
                            icon: 2
                        })
                    }
                })
            },
            // 下载在线简历
            downloadOnline: function (elem) {

                if(elem.attr('disabled')) {
                    return false
                }

                var userName = $('input.userName').val();
                var xhr = new XMLHttpRequest();
                xhr.open("POST", API_BASE_URL + '/userCenter/generalPersonalResume', true);
                xhr.setRequestHeader('Authorization', "bearer " + getCookie('USER_TOKEN'));
                xhr.responseType = 'blob';
                xhr.onreadystatechange = function (){
                    if(xhr.readyState === 4){
                        if((xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)){
                            var blob = xhr.response;
                            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                                window.navigator.msSaveOrOpenBlob(blob, '');
                            }else{
                                var objUrl = URL.createObjectURL(blob),
                                    downEl = document.createElement('a');
                                downEl.href = objUrl;
                                downEl.download = userName + '简历【51语言】.docx';
                                downEl.target = '_blank';
                                downEl.style.display = 'none';
                                document.body.append(downEl);
                                downEl.click();
                                downEl.remove();
                                URL.revokeObjectURL(objUrl)
                            }
                        }
                        elem.removeAttr('disabled');
                        layer.closeAll('loading')
                    }
                };
                xhr.send(null);
                elem.attr('disabled', true);
                layer.msg('正在生成简历文件，请稍等', {
                    icon: 16
                    ,shade: 0.01
                })
            }
        };

        thisObj.init();


        // scroll定位
        var ScrollPosition = function () {
            this.init()
        };

        ScrollPosition.prototype = {
            constructor: ScrollPosition,
            // 初始化
            init: function () {

                this.items = $('.resume-item');
                this.itemsNav = $('.position_nav');
                this.DEFAULT_TOP = 64;

                this.position()
            },
            // 定位，标记当前活动resume-item
            position: function (){
                var item = null,
                    itemTop = 0,
                    itemBottom = 0;
                for(var i = 0; i < this.items.length; i++){
                    item = this.items[i];
                    itemTop = item.getBoundingClientRect().top - this.DEFAULT_TOP;
                    itemBottom = item.getBoundingClientRect().bottom - this.DEFAULT_TOP;
                    if(itemTop <= 0 && itemBottom > 0 || (itemTop >= 0 && itemBottom >= 0)){
                        this.itemsNav.eq(i)
                                     .addClass('current')
                                     .siblings().removeClass('current');
                        return
                    }
                }
            }
        };

        var scroll = new ScrollPosition();

        // 为 window 对象添加事件代理
        $(window).on({
            'click': function (e){
                var $tar = $(e.target);
                // 所有下拉框
                if($tar.hasClass('selectMenu')){
                    thisObj.dispatchSelect(e.target)
                }
                // 下拉框，薪资范围选择
                if($tar.hasClass('selectSalary')){
                    thisObj.salaryScaleLimit(e.target)
                }
                // 省市区
                if($tar.hasClass('post_pickerPCA')){
                    thisObj.allProvince(e.target);
                }
                // 国家/地区
                if($tar.hasClass('post_pickerNation')){
                    thisObj.allNation(e.target);
                }
                // 职位类型
                if($tar.hasClass('post_pickerPostType')){
                    thisObj.allPostType(e.target);
                }
                // 工作城市
                if($tar.hasClass('post_pickerCity')){
                    thisObj.allWorkCity(e.target);
                }
                // 行业类别
                if($tar.hasClass('post_pickerIndustry')){
                    thisObj.allIndustry(e.target);
                }
                // 查看大图
                if($tar.hasClass('largeImg')){
                    layer.open({
                        type: 1,
                        title: false,
                        area: ['auto'],
                        skin: 'layui-layer-nobg',
                        shadeClose: true,
                        content: "<img src='"+ $tar.attr('src') +"' style='max-width: 1200px' alt=''>"
                    })
                }
                // fixed导航定位
                if($tar.hasClass('position_nav')){
                    setTimeout(function () {
                        $tar.addClass('current').siblings().removeClass('current')
                    }, 100)
                }
                // 添加 form 表单
                if($tar.hasClass('add_form')){
                    var $currPart = $tar.parent('div').prev(),
                        $itemContainer = $tar.parents('.resume-item'),
                        partId = $currPart.attr('id');
                    if($currPart.length && !$itemContainer.find('form').length){
                        $itemContainer.append($('#tempt_' + partId).html());
                        thisObj.renderForm(partId)
                    }
                }
                // 移除 form 表单
                if($tar.hasClass('cancel_form')){
                    $tar.parents('form').remove()
                }
                // 点击 textarea 区域
                if(e.target.nodeName === 'TEXTAREA'){
                    $tar.parent().addClass('hover')
                }else{
                    $('form.layui-form .remark').removeClass('hover')
                }
                // 弹出自定义标签 “模态框”
                if($tar.hasClass('selfDefineLabel')){
                    thisObj.defineLabel($tar)
                }
                // 展示“更多”标签
                if($tar.hasClass('moreLabel')){
                    $tar.parent().toggleClass('more');
                    $tar.html($tar.parent().hasClass('more') ? '收起' : '更多>')
                }
                // 选中/取消标签
                if(e.target.nodeName === 'LABEL' && $tar.parent().hasClass('label')){
                    $tar.toggleClass('selected')
                }
                // 点击上传附件
                if($tar.hasClass('uploadFile')){
                    $('.uploadResumeFile').click()
                }
                // 上传头像，选择文件
                if($tar.hasClass('uploadImage')){
                    $('.uploadImageFile').click()
                }
                // 删除附件简历
                if($tar.hasClass('del_file')){
                    thisObj.resume_filesDel($tar.attr('data-id'))
                }
                // 删除简历信息
                if($tar.hasClass('del_item')){
                    var delID = $tar.attr('data-id'),
                        delType = $tar.attr('data-type');
                    thisObj.resume_itemDel({
                        elem: $tar,
                        name: delType,
                        id: delID
                    })
                }
                // 编辑简历信息
                if($tar.hasClass('edit_item')){
                    var partId = $tar.attr('data-type'),
                        $itemContainer = $tar.parents('.resume-item'),
                        $item = $tar.parents('.item');
                    if(!$itemContainer.find('form').length){
                        if($tar.hasClass('edit_lan')){
                            $itemContainer.append($('#tempt_' + partId).html())
                        }else{
                            $item.after($('#tempt_' + partId).html());
                        }
                        thisObj.renderForm();
                        thisObj.dispatchEdit(partId, $tar.next('.data').html())
                    }
                }
                // 编辑/隐藏，基本信息/自我评价form表单
                if($tar.hasClass('toggle_form')){
                    var $parents = $tar.parents('.resume-item'),
                        $fillElem = $parents.find('.fillItem'),
                        $infoElem = $parents.find('.infoItem');
                    var _data = $tar.next('.data').html();
                    if(!$infoElem.length) return false;
                    if($tar.hasClass('edit-icon')){
                        $fillElem.removeClass('hidden');
                        $infoElem.addClass('hidden');
                        if($tar.hasClass('base_form')){
                            thisObj.fill_resume_addBase(_data)
                        }else{
                            thisObj.fill_resume_addLabel(_data)
                        }
                    }else{
                        $fillElem.addClass('hidden');
                        $infoElem.removeClass('hidden')
                    }
                }
                // 提交上传证书
                if($tar.hasClass('upload_certificate_btn')){
                    thisObj.certificateUpload($tar)
                }
                // 保存在线简历
                if($tar.hasClass('download')){
                    thisObj.downloadOnline($tar)
                }
            },
            'change': function (e){
                var $tar = $(e.target);
                //上传附件
                if($tar.hasClass('uploadResumeFile')){
                    thisObj.upload_resumeFile(e.target)
                }
                // 上传头像
                if($tar.hasClass('uploadImageFile')){
                    uploadImage(e.target, thisObj.userID)
                }
                // 选择证书文件
                if($tar.hasClass('choseCertificateFile')){
                    thisObj.certificateChoseFile(e.target)
                }
                // 技能证书，select change监听
                if($tar.hasClass('select')){
                    var value = $tar.val(),
                        html = '',
                        initSelect = [];
                    // 其他类证书
                    if($tar.hasClass('otherCertificate')){
                        var $input = $tar.next();
                        if(value === '其他'){
                            $input.removeClass('hidden')
                        }else{
                            $input.addClass('hidden').val('')
                        }
                    }
                    // 语言类证书
                    if($tar.hasClass('languageType')){ // 语种
                        html = '<option value="">请选择证书名称</option>';
                        initConfig.allCertificate.forEach(item => {
                            if(item.languageName === value && item.certificateName){
                                initSelect.push(item)
                            }
                        });
                        if(value && value !== '其他'){
                            initSelect.forEach(item => {
                                html += `<option value="${item.certificateName}">${item.certificateName}</option>`
                            })
                        }
                        $('select.certificateLevel').html(`<option value="">请选择证书等级</option>`);
                        $('select.certificateName').html(html);
                        if(value === '其他'){
                            $('.certificateWrap').removeClass('hidden')
                        }else{
                            $('.certificateWrap').addClass('hidden')
                        }
                        $('.certificateWrap>input')
                            .removeClass('hidden')
                            .val('')
                    }
                    if($tar.hasClass('certificateName')){ // 证书名称
                        for(let i = 0; i < initConfig.allCertificate.length; i++){
                            let item = initConfig.allCertificate[i];
                            if(item.certificateName === value && item.certificateLevel){
                                initSelect = item.certificateLevel.split('、')
                            }
                        }
                        initSelect.forEach(item => {
                            html += `<option value="${item}">${item}</option>`
                        });
                        if(!value){
                            html = '<option value="">请选择证书等级</option>'
                        }else{
                            if(!html){
                                html = '<option value="无">无</option>'
                            }
                        }
                        $('select.certificateLevel').html(html);
                        if(value === '其他'){
                            $('.certificateWrap').removeClass('hidden');
                            $('.certificateWrap>input').eq(0).addClass('hidden')
                        }else{
                            $('.certificateWrap').addClass('hidden');
                            $('.certificateWrap>input').val('')
                        }
                    }
                }
            },
            'input': debounce(function (e){
                var $tar = $(e.target);
                // 长度限制
                if($tar.hasClass('maxPutLength')){
                    var $maxLen = $tar.next('.maxLength'),
                        maxLen = $maxLen.attr('data-max');
                    maxInput($tar, $maxLen, maxLen, function (){
                        layer.msg(`输入内容长度超过${maxLen}字符`, {icon: 5})
                    })
                }
            }, 500),
            'scroll': debounce(function () {

                scroll.position()

            }, 50)
        })
    };

    // 全局替换
    window.gb_config_obj = gb_config;

})(window.gb_config_obj || {}, jQuery, window, document);